<?php
/**
 * 客户端auth登陆权限基础类库
 *    1、每个接口(需要登录  个人中心 点赞 评论）都需要去集
 *    2、判定 access_user_token 是否合法
 *    3、用户信息 - 》 user
 * User: sunlight
 * Date: 2018/11/26
 * Time: 15:42
 */

namespace app\api\controller\V1;

use app\api\controller\Common;
use app\common\lib\Aes;
use app\common\lib\exception\ApiException;

class AuthBase extends Common{

    /**
     * 登陆用户的基本信息
     * @var array
     */
    public $user=[];

    /**
     * 初始化
     * @throws ApiException
     * @throws \think\exception\DbException
     */
    public function _initialize(){
        parent::_initialize();
        if (empty($this->isLogin())){
            throw new ApiException('您没有登录', 401);
        }
    }

    /**
     * 判定是否登陆
     * @return bool
     * @throws \think\exception\DbException
     */
    public function isLogin(){
        halt($this->headers);
        if (empty($this->headers['use78r_token'])){
            return false;
        }

        $obj=new Aes();
        $accessUserToken=$obj->decrypt($this->headers['access_user_token']);
//halt($accessUserToken);
        if (empty($accessUserToken)){
            return false;
        }

        if (!preg_match('/||/',$accessUserToken)){
            return false;
        }

        list($token,$id)=explode("||",$accessUserToken);
        $user=\app\common\model\User::get(['token'=>$token]);
        //echo $user;exit;
        //halt($this->user = $user);
        if (!$user || $user->status!=1){
            echo "进来没";
            return false;
        }

        //判断时间是否过期
        if (time()>$user->time_out){
            return false;
        }

        $this->user = $user;
        return true;
    }

}